package com.fone.player.activity.personal;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.LoginRst;
import com.fone.player.client.Reporter;
import com.fone.player.client.Request;
import com.fone.player.constant.FoneConstant;
import com.fone.player.entity.Download;
import com.fone.player.storage.SharedPreferenceModule;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.GetFileSizeUtil;
import com.fone.player.util.L;
import com.fone.player.util.SystemUtil;
import com.fone.player.view.LegalNoticeDialog;

public class SettingActivity extends BaseActivity implements OnClickListener {

	private static final String TAG = "SettingActivity";
	private Context mContext;

	private TextView mTitleTv, mCurrentVersion, mIsNewVersion;
	private Button mLeftBt, mRightBt;
	public static final int TYPE_LAW = 1;
	public static final int TYPE_ABOUT = 2;

	private RelativeLayout setting_feedback_rl, setting_about_rl,
			setting_current_version_rl, setting_law_declaration_rl;
	private CheckBox mNotifySwitchCb;
	private Button mCleanCacheBt;

	private SharedPreferences mSp;
	private SettingCallBack callBack;

	public static final String SUGGEST_UPDATE = "0"; // 推荐升级
	public static final String FORCE_UPDATE = "1"; // 强制升级
	public static final String ALREADY_NEWLEST = "2"; // 已是最新版本

	private String updateUrl;
	private LoginRst loginRst;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.personal_setting_view);
		mContext = getApplicationContext();
		mSp = mContext.getSharedPreferences(FoneConstant.FONE_SP_NAME_SP,
				Activity.MODE_PRIVATE);
		initView();
		initData();
	}

	private void initData() {

		// 设置当前版本信息
		mCurrentVersion.setText("当前版本(" + SystemUtil.getAppVersion(mContext)
				+ ")");
		String folderSize = "0M";
		try {

			if (GetFileSizeUtil
					.getInstance()
					.getFileSizeByPath(
							SystemUtil
									.getFoneCacheFolder(SystemUtil.ONLINE_CACHE_TYPE)) == 0) {
				folderSize = "0M";
			} else {
				folderSize = GetFileSizeUtil
						.getInstance()
						.getFileSizeByPathFormat(
								SystemUtil
										.getFoneCacheFolder(SystemUtil.ONLINE_CACHE_TYPE));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		mCleanCacheBt.setText("清理(" + folderSize + ")");

		callBack = new SettingCallBack();

		Request.getInstance().login(1, callBack);

	}

	private void initView() {
		mLeftBt = (Button) findViewById(R.id.common_title_left_bt);
		mRightBt = (Button) findViewById(R.id.common_title_right_bt);
		mTitleTv = (TextView) findViewById(R.id.common_title_text_tv);

		mLeftBt.setText("设置");
		mRightBt.setVisibility(View.GONE);
		mTitleTv.setVisibility(View.GONE);
		mCleanCacheBt = (Button) findViewById(R.id.setting_version_check_tv);
		mCleanCacheBt.setOnClickListener(this);

		mIsNewVersion = (TextView) findViewById(R.id.setting_version_code_tv);
		mCurrentVersion = (TextView) findViewById(R.id.setting_current_version_tv);

		setting_feedback_rl = (RelativeLayout) findViewById(R.id.setting_feedback_rl);
		setting_about_rl = (RelativeLayout) findViewById(R.id.setting_about_rl);
		setting_law_declaration_rl = (RelativeLayout) findViewById(R.id.setting_law_declaration_rl);
		setting_current_version_rl = (RelativeLayout) findViewById(R.id.setting_current_version_rl);
		mNotifySwitchCb = (CheckBox) findViewById(R.id.setting_notify_switch_cb);

		mNotifySwitchCb.setChecked(mSp.getBoolean(
				FoneConstant.NOTIFY_SWITCH_FLAG_SP, true));

		setting_feedback_rl.setOnClickListener(this);
		setting_about_rl.setOnClickListener(this);
		setting_current_version_rl.setOnClickListener(this);
		setting_law_declaration_rl.setOnClickListener(this);
		mLeftBt.setOnClickListener(this);
		mNotifySwitchCb
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// 记录通知开关
						mSp.edit()
								.putBoolean(FoneConstant.NOTIFY_SWITCH_FLAG_SP,
										isChecked).commit();

					}
				});

	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.setting_feedback_rl:
			intent = new Intent(this, FeedBackActivity.class);
			startActivity(intent);
			break;
		case R.id.setting_version_check_tv:
			// 清理缓存文件夹大小
			doCleanCacheFolder();
			break;
		case R.id.common_title_left_bt:
			finish();

			break;
		case R.id.setting_current_version_rl:
			if (null != updateUrl) {
				// Reporter.logEvent(Reporter.EventId.UPGRADE_SELF_CHECK);

				SharedPreferenceModule.getInstance().setBoolean(
						"upgrade_self_check", true);
				Download download = StorageModule.getInstance().getDownload(
						loginRst.softupdate.updateurl);
				if (download != null) {
					SharedPreferenceModule.getInstance().setString(
							FoneConstant.UPDATE_VERSION,
							SystemUtil.getAppVersion(mContext));
					if (download.getDownloadStateType() == Download.DOWNLOAD_STATE_FINISH) {
						StorageModule.getInstance().installApp(
								download.getDownloadStoragePath(),
								download.getDownloadUrl());
					} else {
						download.setDownloadIsShowRunningNotification(true);
						download.setDownloadNotification(mContext);
						download.setDownloadIsInstall(true);
						download.setDownloadIsErrorToast(true);
						StorageModule.getInstance()
								.updateFileDownload(download);
						FoneUtil.showToast(mContext, "已经添加到缓存队列了");
					}
				} else {
					download = new Download();
					download.setDownloadIsShowRunningNotification(true);
					download.setDownloadNotification(SettingActivity.this);
					download.setDownloadUrl(updateUrl);
					download.setDownloadIsInstall(true);
					download.setDownloadIsErrorToast(true);
					download.setDownloadIsLimitSpeed(false);
					download.setDownloadFileName(loginRst.softupdate.name);
					download.setDownloadType(Download.DOWNLOAD_UPGRADE);

					int addstate = StorageModule.getInstance().addFileDownload(
							download);
					// int 操作结果 1 添加成功 0 服务未启动 -1 任务已存在 -2添加异常
					switch (addstate) {
					case -1:
						FoneUtil.showToast(mContext, "已经添加到缓存队列了");
						break;
					case 1:
						FoneUtil.showToast(mContext, "正在下载升级包");
						break;
					}
				}
			} else {
				Toast.makeText(mContext, "当前已经是最新版本了~", Toast.LENGTH_SHORT)
						.show();
			}

			break;
		case R.id.setting_about_rl:
			Intent aboutIntent = new Intent(this, HelpAndAboutActivity.class);
			aboutIntent.putExtra("type", TYPE_ABOUT);
			startActivity(aboutIntent);
			break;
		case R.id.setting_law_declaration_rl:
			// Intent lawIntent = new Intent(this, HelpAndAboutActivity.class);
			// lawIntent.putExtra("type", TYPE_LAW);
			// startActivity(lawIntent);
			new LegalNoticeDialog(SettingActivity.this,
					FoneUtil.getDeclaration(SettingActivity.this,
							FoneConstant.SETTING_LEGAL_NOTICE));
			break;

		default:
			break;
		}

	}

	/**
	 * 清理缓存文件夹
	 * 
	 * @return void
	 * @throws
	 */
	private void doCleanCacheFolder() {
		long fileSize = 0;
		String path = SystemUtil
				.getFoneCacheFolder(SystemUtil.ONLINE_CACHE_TYPE);
		try {
			fileSize = GetFileSizeUtil.getInstance().getFileSizeByPath(path);
		} catch (Exception e) {
			e.printStackTrace();

		}
		if (fileSize > 0) {
			SystemUtil.delAllFile(path);
			mCleanCacheBt.setText("清理(0M)");
			FoneUtil.showToast(mContext, "开始清理临时文件");
		} else {
			FoneUtil.showToast(mContext, "当前没有缓存文件");
		}
	}

	private class SettingCallBack implements Callback<LoginRst> {

		@Override
		public void onSuccess(LoginRst t) {
			L.v("JasonZue", "loginRequestRST:" + t.toString());
			if (t.result != 0) {
				// FIXME 发正式包前需处理掉!
				FoneUtil.showToast(mContext, "获取数据失败");
			} else {
				loginRst = t;
				if (ALREADY_NEWLEST.equals(t.softupdate.updateflag)) {
					mIsNewVersion.setText("已是最新版本");
				} else if (SUGGEST_UPDATE.equals(t.softupdate.updateflag)) {
					// 强制升级和推荐升级做的同样的处理 (逻辑上此处不应该出现强制升级)
					mIsNewVersion.setText("点击升级到" + t.softupdate.name);
					updateUrl = t.softupdate.updateurl;
				} else if (FORCE_UPDATE.equals(t.softupdate.updateflag)) {
					// 强制升级和推荐升级做的同样的处理 (逻辑上此处不应该出现强制升级)
					mIsNewVersion.setText("点击升级到" + t.softupdate.name);
					updateUrl = t.softupdate.updateurl;
				} else {
					mIsNewVersion.setText("已是最新版本");
				}
			}
		}

		@Override
		public void onFailure(Error error) {
			L.v(TAG,
					"LoginCallBack onFailure",
					"isNetworkError : " + error.isNetworkError() + " status : "
							+ error.getStatus() + " reason : "
							+ error.getReason());
		}
	}

}
